import os
import json
from PyQt5.QtCore import QObject, QRunnable, pyqtSignal, QThreadPool
from core.connectors.db_connector import DatabaseConnector
from core.generator.data_generator import DataGenerator


class DataGenerationTaskSignals(QObject):
    """
    信号类，用于 DataGenerationTask 发出信号。
    """
    progress_signal = pyqtSignal(int, dict, str)  # (行号, 新记录数, 状态(success, error))
    start_signal = pyqtSignal(int, str)  # 当前行开始处理


class DataGenerationTask(QRunnable):
    """
    单表数据生成任务。
    """
    def __init__(self, row, table, db_connector, config):
        super().__init__()
        self.row = row
        self.table = table
        self.db_connector = db_connector
        self.config = config
        self.signals = DataGenerationTaskSignals()
        self.is_running = True  # 任务运行标志

    def stop(self):
        """
        停止任务。
        """
        self.is_running = False

    def run(self):
        if not self.is_running:
            return
        """
        任务逻辑：为单张表生成数据。
        """
        try:
            # 加载策略文件路径
            strategy_save_path = self.config.get("strategy_save_path", "./strategies")
            strategy_file = os.path.join(strategy_save_path, f"{self.db_connector.get_connector_name()}_{self.table}.json")

            # 检查策略文件是否存在
            if not os.path.exists(strategy_file):
                error_details = {
                    "table": self.table,
                    "success_count": 0,
                    "failure_count": 1,
                    "failure_details": f"策略文件 {strategy_file} 不存在"
                }
                self.signals.progress_signal.emit(self.row, error_details, "error")
                return

            # 加载策略文件
            try:
                with open(strategy_file, "r", encoding="utf-8") as file:
                    strategy = json.load(file)
            except Exception as e:
                error_details = {
                    "table": self.table,
                    "success_count": 0,
                    "failure_count": 1,
                    "failure_details": f"加载策略文件失败: {e}"
                }
                self.signals.progress_signal.emit(self.row, error_details, "error")
                return

            # 发出开始信号
            self.signals.start_signal.emit(self.row, "yellow")

            # 获取连接器和数据生成器
            data_generator = DataGenerator.create_generator(self.db_connector,self.config)

            # 调用数据生成逻辑
            process_result = data_generator.generate_test_data_for_table(self.db_connector,self.table,strategy)

            # 发出成功信号
            self.signals.progress_signal.emit(self.row, process_result, "success")
        except Exception as e:
            # 捕获异常并发出错误信号
            error_details = {
                "table": self.table,
                "success_count": 0,
                "failure_count": 1,
                "failure_details": e
            }
            self.signals.progress_signal.emit(self.row, error_details, "error")


class DataGenerationManager:
    """
    数据生成管理器，用于管理线程池和任务。
    """
    def __init__(self, tables, db_connector, config):
        self.tables = tables
        self.db_connector = db_connector
        self.config = config
        self.thread_pool = QThreadPool.globalInstance()
        self.tasks = []  # 存储所有任务实例

    def start(self, start_signal, progress_signal):
        """
        启动线程池任务。
        :param start_signal: 行号和颜色的开始信号
        :param progress_signal: 行号、生成结果和状态的进度信号
        """
        for row, table in self.tables:
            task = DataGenerationTask(row, table, self.db_connector, self.config)

            # 连接信号
            task.signals.start_signal.connect(start_signal)
            task.signals.progress_signal.connect(progress_signal)

            # 保存任务实例
            self.tasks.append(task)

            # 启动任务
            self.thread_pool.start(task)

    def stop(self):
        """
        停止所有任务。
        """
        for task in self.tasks:
            task.stop()  # 停止每个任务
        self.tasks.clear()  # 清空任务列表